package com.yzh;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * @author 于振晗
 * @title: GetXmlTest
 * @description: TODO 获取xml值测试
 * @date 2020年09月08日
 * @path com.yzh
 */
public class GetXmlTest {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        //创建DOM解析器工厂
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //通过工厂创建DOM\解析器
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        //解析文档
        Document parse = documentBuilder.parse("Java_Xml/test.xml");
        //获取元素列表
        NodeList products = parse.getElementsByTagName("products");
        //获取第个元素
        Node item = products.item(0);
        //接下来是他的下面子节点
        NodeList childNodes = item.getChildNodes();
        //遍历子节点
        for (int i = 0; i < childNodes.getLength(); i++) {
            //获取当前节点是否为
            Node item1 = childNodes.item(i);
            //判断当前节点是否为元素节点
            if (item1.getNodeType() == Node.ELEMENT_NODE) {
                //元素节点转换为元素
                Element el = (Element)item;
                System.out.println(el.getAttribute("id"));
////                System.out.println("id = "+id);
            }
        }
    }
}
